<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑案件当事人' : '添加案件当事人'"
    width="800px"
    :close-on-click-modal="false"
    :before-close="handleClose"
    class="party-add-dialog"
  >
    <div class="dialog-content">
      <!-- 添加模式下显示选择器标签页 -->
      <template v-if="!isEdit">
        <!-- 简化版标签页导航 -->
        <el-alert
          title="请使用优化的当事人选择器添加当事人"
          type="info"
          :closable="false"
          show-icon
          class="info-alert"
        />
        <div class="info-text">
          <p>为了提供更好的用户体验，我们已将当事人添加功能整合到优化的选择器中。</p>
          <p>请关闭此对话框，使用案件详情页面的"添加当事人"按钮来添加新的当事人。</p>
        </div>
      </template>

      <!-- 当事人表单（仅在编辑模式下显示） -->
      <div class="party-form-container">
        <PartyForm
          ref="editPartyFormRef"
          v-if="isEdit"
          :partyData="props.formData"
          :isEdit="true"
          :caseId="props.caseId"
          :loading="loading"
          @validate="handleFormValidate"
          @success="handleFormSuccess"
        />
        <div v-else class="add-party-info">
          <p>请使用优化的当事人选择器添加当事人</p>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" :disabled="loading">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="loading"
          :disabled="!canSubmit"
          v-if="isEdit"
        >
          确认更新
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 重复确认对话框 -->
  <el-dialog
    v-model="duplicateDialogVisible"
    title="当事人已存在"
    width="500px"
    class="duplicate-confirm-dialog"
  >
    <div class="duplicate-content">
      <el-alert title="发现重复当事人" type="warning" :closable="false" show-icon />
      <div class="duplicate-info" v-if="duplicateParty">
        <p>
          <strong>当事人名称：</strong>
          {{ duplicateParty.name }}
        </p>
        <p>
          <strong>证件号码：</strong>
          {{ duplicateParty.idNumber }}
        </p>
        <p>
          <strong>当事人类型：</strong>
          {{ duplicateParty.type }}
        </p>
      </div>
      <p class="duplicate-tip">是否继续添加该当事人？</p>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="duplicateDialogVisible = false">取消</el-button>
        <el-button type="warning" @click="forceAddParty">继续添加</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, computed, watch, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import PartyForm from './PartyForm.vue'
  import request from '@/utils/request'

  // 定义接口
  interface PartyFormData {
    name: string
    type: '个人' | '企业'
    idNumber: string
    contactName: string
    contactPhone: string
    address: string
    email: string
    remark: string
  }

  interface EditPartyData {
    id: number
    case_id: number
    party_id: number
    name: string
    party_type: number
    id_number: string
    contact: string
    mobile: string
    address: string
    email: string
    remark: string
    is_client: number
    relationship: number
  }

  interface DuplicateParty {
    name: string
    idNumber: string
    type: string
  }

  interface Customer {
    id: number
    name: string
    customer_type: 15 | 16
    contact_name: string
    contact_mobile: string
    address: string
    email: string
    // 添加可能的其他字段
    [key: string]: any
  }

  // Props和Emits
  const props = defineProps<{
    modelValue: boolean
    caseId: number | undefined
    isEdit?: boolean
    formData?: EditPartyData
  }>()

  const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    success: [partyData: PartyFormData]
    close: []
  }>()

  // 使用computed确保isEdit保持响应式
  const isEdit = computed(() => props.isEdit || false)

  // 响应式数据
  const loading = ref(false)
  const localFormData = ref<PartyFormData>({
    name: '',
    type: '个人',
    idNumber: '',
    contactName: '',
    contactPhone: '',
    address: '',
    email: '',
    remark: '',
  })

  const duplicateDialogVisible = ref(false)
  const duplicateParty = ref<DuplicateParty | null>(null)

  // 引用子组件
  const editPartyFormRef = ref<InstanceType<typeof PartyForm> | null>(null)

  // 计算属性
  const dialogVisible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const canSubmit = computed(() => {
    // 在编辑模式下，只要有案件ID就可以提交，因为表单数据通过props传递
    return isEdit.value ? props.caseId !== undefined : false
  })

  // 监听编辑表单数据变化
  watch(
    () => props.formData,
    newData => {
      if (props.isEdit && newData) {
        console.log('编辑模式下接收到的当事人数据:', newData)
        // 在编辑模式下，确保editPartyFormRef组件能够正确接收到数据
        // 由于我们使用props直接传递，这里需要确保响应式更新
        nextTick(() => {
          // 强制触发表单数据更新
          if (editPartyFormRef.value && typeof editPartyFormRef.value.refreshForm === 'function') {
            editPartyFormRef.value.refreshForm(newData)
          }
        })
      }
    },
    { immediate: true, deep: true }
  )

  const checkDuplicate = async (): Promise<boolean> => {
    try {
      const response: any = await request.get('/api/lawcase/parties/check_duplicate', {
        params: {
          name: localFormData.value.name,
          id_number: localFormData.value.idNumber,
        },
      })

      if (response.data.code === 0 && response.data.exists) {
        duplicateParty.value = {
          name: localFormData.value.name,
          idNumber: localFormData.value.idNumber,
          type: localFormData.value.type,
        }
        duplicateDialogVisible.value = true
        return true
      }
      return false
    } catch (error) {
      console.error('检查重复当事人失败:', error)
      return false
    }
  }

  const forceAddParty = () => {
    duplicateDialogVisible.value = false
    submitParty(true)
  }

  const submitParty = async (force = false) => {
    if (!props.caseId) {
      ElMessage.error('案件ID不能为空')
      return
    }

    loading.value = true
    try {
      // 调用对应的PartyForm组件的submitForm方法
      if (isEdit.value && editPartyFormRef.value) {
        // 编辑模式，调用编辑表单的提交方法
        await editPartyFormRef.value.submitForm(force)
      } else {
        // 如果组件引用不可用，使用原有的提交逻辑
        const partyData = {
          case_id: props.caseId,
          name: localFormData.value.name,
          party_type: localFormData.value.type === '企业' ? 2 : 1,
          id_number: localFormData.value.idNumber,
          contact: localFormData.value.contactName,
          phone: localFormData.value.contactPhone,
          address: localFormData.value.address,
          email: localFormData.value.email,
          remark: localFormData.value.remark,
          force: force ? 1 : 0,
        }

        let response: any
        if (isEdit.value && props.formData) {
          // 编辑模式，调用编辑API
          const editData = {
            ...partyData,
            id: props.formData.id,
            party_id: props.formData.party_id,
          }
          response = await request.put('/api/lawcase/parties/update_party', editData)
        } else {
          // 添加模式，调用添加API
          response = await request.post('/api/lawcase/parties/add_to_case', partyData)
        }

        if (response.data.code === 0) {
          ElMessage.success(isEdit.value ? '更新当事人成功' : '添加当事人成功')
          // 直接调用handleFormSuccess统一处理成功逻辑
          handleFormSuccess(localFormData.value)
        } else {
          ElMessage.error(response.data.msg || (isEdit.value ? '更新当事人失败' : '添加当事人失败'))
        }
      }
    } catch (error) {
      console.error(isEdit.value ? '更新当事人失败:' : '添加当事人失败:', error)
      ElMessage.error(isEdit.value ? '更新当事人失败' : '添加当事人失败')
    } finally {
      loading.value = false
    }
  }

  const handleSubmit = async () => {
    if (isEdit.value) {
      // 编辑模式下直接提交，跳过重复检查
      submitParty()
    } else {
      // 添加模式下检查是否重复
      const isDuplicate = await checkDuplicate()
      if (isDuplicate && !duplicateDialogVisible.value) {
        return
      }

      if (!isDuplicate) {
        submitParty()
      }
    }
  }

  const handleClose = () => {
    // 通过emit触发update:modelValue事件来关闭对话框，这是Vue 3 v-model的正确使用方式
    emit('update:modelValue', false)
    // 通知父组件对话框已关闭
    emit('close')
  }

  const handleFormValidate = (isValid: boolean) => {
    // 表单验证回调
  }

  const handleFormSuccess = (partyData: any) => {
    // 当PartyForm提交成功时，触发父组件的success事件，让父组件刷新数据
    emit('success', partyData)
    // 延迟一小段时间再关闭对话框，确保父组件有足够时间处理刷新
    setTimeout(() => {
      handleClose()
    }, 300)
  }

  // 暴露方法给父组件
  defineExpose({
    handleClose,
  })
</script>

<style scoped>
  .info-alert {
    margin-bottom: 20px;
  }

  .info-text {
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .info-text p {
    margin: 10px 0;
    line-height: 1.6;
  }

  .add-party-info {
    text-align: center;
    padding: 40px 20px;
    color: #909399;
  }
</style>
